﻿using Andy.Web.CauHinhServiceReference;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Andy.Web.admin
{
    public partial class ht_sua_cauhinh : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadCauHinhTrangChu();
            }
        }
        public void loadCauHinhTrangChu()
        {
            using (var chService = new CauHinhServiceReference.CauHinhServiceClient())
            {
                var ch = chService.ChiTietCauHinh();
                if (ch != null)
                {
                    txtTitle.Text = ch.Text2;
                    txtTileMenu.Text = ch.Text1;
                    txtTitleSanPham.Text = ch.Text3;
                    txtHuongDan.Text = ch.Text4;
                    txtMaMau.Text = ch.Text5;
                    imgHuongDan.Src ="../"+ch.Image1;
                    imgLogo.Src = "../"+ch.Image2;
                    hdfID.Value = ch.Id.ToString();
                }
            }
        }
        protected void btLuu_Click(object sender, EventArgs e)
        {
            string strfileUploader = null;
            string strfileUploadlogo = null;
            if (fileUploader.PostedFile != null)
            {
                var date = DateTime.Now.ToString("yyyyMMddhhmmss");
                string filePath = "~\\Images\\" + date;
                //string thumbPath = "~\\Images\\" + date + "_thumb";


                // Check file size (mustn’t be 0)
                HttpPostedFile myFile = fileUploader.PostedFile;
                int nFileLen = myFile.ContentLength;
                if ((nFileLen > 0) && (System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".jpg"))
                {
                    // Read file into a data stream
                    byte[] myData = new Byte[nFileLen];
                    myFile.InputStream.Read(myData, 0, nFileLen);
                    myFile.InputStream.Dispose();

                    // Save the stream to disk as temporary file. make sure the path is unique!
                    System.IO.FileStream newFile
                            = new System.IO.FileStream(Server.MapPath(filePath + "_temp.jpg"),
                                                       System.IO.FileMode.Create);
                    newFile.Write(myData, 0, myData.Length);

                    // run ALL the image optimisations you want here..... make sure your paths are unique
                    // you can use these booleans later if you need the results for your own labels or so.
                    // dont call the function after the file has been closed.
                    bool success = ResizeImageAndUpload(newFile, filePath, 300, 200);
                    // tidy up and delete the temp file.
                    newFile.Close();
                    System.IO.File.Delete(Server.MapPath(filePath + "_temp.jpg"));
                    strfileUploader="Images/" + date+".jpg";
                }
            }
            if (fileUploadlogo.PostedFile != null)
            {
                var date = DateTime.Now.ToString("yyyyMMddhhmmss");
                string filePath = "~\\Images\\" + date;
                


                // Check file size (mustn’t be 0)
                HttpPostedFile myFile = fileUploadlogo.PostedFile;
                int nFileLen = myFile.ContentLength;
                if ((nFileLen > 0) && (System.IO.Path.GetExtension(myFile.FileName).ToLower() == ".jpg"))
                {
                    // Read file into a data stream
                    byte[] myData = new Byte[nFileLen];
                    myFile.InputStream.Read(myData, 0, nFileLen);
                    myFile.InputStream.Dispose();

                    // Save the stream to disk as temporary file. make sure the path is unique!
                    System.IO.FileStream newFile
                            = new System.IO.FileStream(Server.MapPath(filePath + "_temp.jpg"),
                                                       System.IO.FileMode.Create);
                    newFile.Write(myData, 0, myData.Length);

                    // run ALL the image optimisations you want here..... make sure your paths are unique
                    // you can use these booleans later if you need the results for your own labels or so.
                    // dont call the function after the file has been closed.
                    bool success = ResizeImageAndUpload(newFile, filePath, 50, 245);
                    // tidy up and delete the temp file.
                    newFile.Close();
                    System.IO.File.Delete(Server.MapPath(filePath + "_temp.jpg"));
                    strfileUploadlogo="Images/" + date+".jpg";
                }
            }
            var ch = new CauHinh();
            string result = "";
            using (var chService = new CauHinhServiceReference.CauHinhServiceClient())
            {
                if (!string.IsNullOrEmpty(hdfID.Value))
                {
                    ch.Id = Convert.ToInt64(hdfID.Value);
                    ch.Image1 = strfileUploader;
                    ch.Image2 = strfileUploadlogo;

                    ch.Text2 = txtTitle.Text;
                    ch.Text1 = txtTileMenu.Text;
                    ch.Text3 = txtTitleSanPham.Text;
                    ch.Text4 = txtHuongDan.Text;
                    ch.Text5 = txtMaMau.Text;
                    result += chService.CapNhatCauHinh(ch);
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Redit", "alert('" + result + " !'); window.location='" + Request.ApplicationPath + "admin/ht_sua_cauhinh.aspx';", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Redit", "alert('Cập nhật thất bại. Yêu cầu thử lại sau !'); window.location='" + Request.ApplicationPath + "admin/ht_qlsp.aspx';", true);
                }
            }
        }
        public bool ResizeImageAndUpload(System.IO.FileStream newFile, string folderPathAndFilenameNoExtension, double maxHeight, double maxWidth)
        {

            try
            {

                // Declare variable for the conversion
                float ratio;

                // Create variable to hold the image
                System.Drawing.Image thisImage = System.Drawing.Image.FromStream(newFile);

                // Get height and width of current image
                int width = (int)thisImage.Width;
                int height = (int)thisImage.Height;

                // Ratio and conversion for new size
                if (width > maxWidth)
                {
                    ratio = (float)width / (float)maxWidth;
                    width = (int)(width / ratio);
                    height = (int)(height / ratio);
                }

                // Ratio and conversion for new size
                if (height > maxHeight)
                {
                    ratio = (float)height / (float)maxHeight;
                    height = (int)(height / ratio);
                    width = (int)(width / ratio);
                }

                // Create "blank" image for drawing new image
                Bitmap outImage = new Bitmap(width, height);
                Graphics outGraphics = Graphics.FromImage(outImage);
                SolidBrush sb = new SolidBrush(System.Drawing.Color.White);


                // Fill "blank" with new sized image
                outGraphics.FillRectangle(sb, 0, 0, outImage.Width, outImage.Height);
                outGraphics.DrawImage(thisImage, 0, 0, outImage.Width, outImage.Height);
                sb.Dispose();
                outGraphics.Dispose();
                thisImage.Dispose();

                // Save new image as jpg
                outImage.Save(Server.MapPath(folderPathAndFilenameNoExtension + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
                outImage.Dispose();

                return true;

            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}